<template>
  <div>
    <div class="titleDiv">{{ inConfigTarget.dialogTitle }}</div>
    <el-divider>{{ inConfigTarget.name }}</el-divider>
    <el-row class="configItemDiv">
      <div class="configItemTitle">{{ inConfigTarget.itemTitle }}</div>
      <el-row v-for="itemRow in configAry" :key="itemRow.id">
        <el-row>
          {{ itemRow.title }}
        </el-row>
        <el-row v-if="inConfigTarget.type==='checkbox'">
          <el-col v-for="item in itemRow.checkItem" :key="item.id" :span="item.col">
            <el-checkbox v-model="item.checked" class="configItem">{{ item.display }}</el-checkbox>
          </el-col>
        </el-row>
        <el-row v-if="inConfigTarget.type==='radio'">
          <el-col v-for="item in itemRow.checkItem" :key="item.id" :span="item.col">
            <el-radio v-model="radio" :label="item.id" class="configItem">{{ item.display }}</el-radio>
          </el-col>
        </el-row>
      </el-row>
    </el-row>
    <el-row v-if="inExtraForm.title!==''" class="extraFormDiv">
      <el-form ref="form" :model="form" label-position="left" label-width="100px">
        <el-form-item v-for="item in inExtraForm.formItem" :key="item.name" :label="item.name">
          <el-input v-model="form[item.name]" />
        </el-form-item>
      </el-form>
    </el-row>
    <el-divider />
    <div class="configButtonDiv">
      <el-button size="mini" class="configButton" @click="$emit('closeConfigPage')">取 消</el-button>
      <el-button type="primary" size="mini" class="configButton" @click="submit">确 认</el-button>
    </div>
  </div>
</template>

<script>
import { getChestsByStationAPI } from '@/util/back_front_api/chests.js'

export default {
  name: 'ConfigPage',
  props: {
    inConfigTarget: {
      type: Object,
      default() {
        return {
          id: '', // 父组件根据数据库得到值，并传入，必填项，不能重复
          name: '！未获取！', // 父组件根据数据库得到值，并传入，必填项
          dialogTitle: '！未获取！', // 父组件传入的值，必填项
          itemTitle: '!未获取!', // 父组件传入的值，必填项
          type: 'checkbox'// 单选或多选，必填项
        }
      }
    },
    inExtraForm: { // 如果需要额外表单，则需要输入此对象
      type: Object,
      default() {
        return {
          title: '', // 父组件传入，如需要额外表单时必填项
          formItem: [
            {
              name: '', // 父组件传入，如需要额外表单时必填项，不能重复
              value: '', // 父组件传入，如需要额外表单时必填项
              validate: '' // value的数值类型，必填，用来校验时候判断用什么验证方式，目前只有chestNo判断。
            }
          ]
        }
      }
    },
    inConfigAry: {
      type: Array,
      default() {
        return [
          { // 选项分类对象，如果有多分类则需要多个对象，一个分类对象下的checkItem包含多个该分类下的选项
            id: '', // 不重复的项，必填项
            title: '', // 根据数据库得到值，并传入，非必填，
            checkItem: [
              { // 选项对象，一个选项一个对象
                id: '', // 不重复的项，必填项
                col: 6, // 组件中计算后获得值
                checked: false, // 父组件根据数据库得到值，并传入，必填项
                display: '' // 父组件根据数据库得到值，并传入，必填项
              }
            ]
          }
        ]
      }
    }
  },
  data() {
    return {
      outObj: {
        targetId: '', // 设置对象的id
        title: '', // 设置的分类
        configId: [], // 勾选的项的id组
        extraForm: {} // 额外表单信息，键值对，键是表单label，值是表单输入的值
      },
      configAry: [],
      form: {},
      radio: '',
      getByStationReq: {
        id: ''
      }
    }
  },
  created() {
    this.arrangeAry()
  },
  methods: {
    async submit() {
      try {
        await this.$confirm('是否确认您刚刚的操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.outObj = {}
        this.outObj.configId = []
        this.outObj.extraForm = []

        this.outObj.targetId = this.inConfigTarget.id
        this.outObj.title = this.inConfigTarget.dialogTitle

        if (this.inConfigTarget.type === 'checkbox') { // outObj.configId整理
          this.inConfigAry.forEach((item1) => {
            item1.checkItem.forEach((item2) => {
              if (item2.checked === true) {
                this.outObj.configId.push(item2.id)
              }
            })
          })
        } else if (this.inConfigTarget.type === 'radio') {
          this.outObj.configId.push(this.radio)
        } else {
          this.utilMessage.warning('选项种类有误')
          return
        }

        if (this.inExtraForm.title !== '') {
          Object.keys(this.form).forEach((key) => { // outObj.extraForm整理
            this.outObj.extraForm[key] = this.form[key]
          })

          for (let i = 0; i < this.inExtraForm.formItem.length; i += 1) { // outObj.extraForm中数值验证
            if (this.inExtraForm.formItem[i].validate === 'chestNo') {
              await this.validateChestNo(this.form[this.inExtraForm.formItem[i].name])
            }
          }
        }
        this.$emit('submitConfig', this.outObj)
      } catch (err) {
        if (err !== 'cancel') {
          this.utilMessage.warning(err)
        } else {
          console.log('请再次选择。', err)
        }
      }
    },
    arrangeAry() {
      this.configAry = []
      this.inConfigAry.forEach(itemRow => {
        let sixColAry = []
        let twelveColAry = []
        let twentyFourColAry = []
        let temp = {}
        itemRow.checkItem.forEach(item => {
          if (item.display.toString().length < 11) { // 转化为字符串来判断display的长度
            item.col = 6
            sixColAry.push(item)
          } else if (item.display.toString().length < 24) {
            item.col = 12
            twelveColAry.push(item)
          } else {
            item.col = 24
            twentyFourColAry.push(item)
          }
        })
        temp.id = itemRow.id
        temp.title = itemRow.title
        temp.checkItem = sixColAry.concat(twelveColAry, twentyFourColAry)
        this.configAry.push(temp)
      })

      if (this.inExtraForm.title !== '') {
        this.inExtraForm.formItem.forEach((item) => {
          this.$set(this.form, item.name, item.value.toString()) // 数值变为字符串型，方便验证计算
        })
      }

      if (this.inConfigTarget.type === 'radio') {
        this.inConfigAry.forEach((item1) => {
          item1.checkItem.forEach((item2) => {
            if (item2.checked === true) {
              this.radio = item2.id
            }
          })
        })
      }
    },
    validateChestNo(value) {
      return new Promise((resolve, reject) => {
        if (value === '') {
          reject(new Error('请输入智能柜柜号'))
        } else {
          value = parseFloat(value)
          if (Number.isInteger(value)) {
            if (value <= 0) {
              reject(new Error('智能柜柜号必须大于零'))
            } else {
              let chestsByStationAryTemp = []
              this.getByStationReq.id = this.outObj.configId[0]
              getChestsByStationAPI(this.getByStationReq).then((result) => {
                chestsByStationAryTemp = result.data
                for (let j = 0; j < chestsByStationAryTemp.length; j += 1) {
                  if (chestsByStationAryTemp[j].chestNo === value) {
                    reject(new Error('智能柜柜号重复'))
                  }
                }
                resolve()
              }).catch((err) => {
                reject(err)
              })
            }
          } else {
            reject(new Error('智能柜柜号必须是整数'))
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.titleDiv {
  text-align: center;
  margin: 0px 0px 20px 0px;
}
.configItemTitle {
  margin: 0px 0px 10px 0px;
}
.configItemDiv {
  height: 300px;
  overflow-y: auto;
  padding: 0px 10px 0px 10px;
}
.extraFormDiv {
  padding: 0px 100px 0px 100px;
}
.configItem {
  font-size: 16px;
  margin: 10px 5px 10px 0px;
}
.configButtonDiv {
  text-align: center;
}
.configButton {
  margin: 0px 30px 0px 30px;
}
// 滚动条修改
::-webkit-scrollbar {
  width:3px;
}
::-webkit-scrollbar-thumb{
  background: #bcddff;
  border-radius: 5px;
}
</style>
